<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  

  
  <title>Hexo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="scala第一天课堂笔记 0. 大纲 Scala简介  Scala安装验证  Scala IDE  Scala基础知识和语法  Scala控制结构  Scala函数  Scala数组&amp;集合   1. Scala简介   Scala是一门多范式（multi-paradigm）的编程语言，设计初衷是要集成面向对象编程和函数式编程的各种特性。   Scala运行在Java虚拟机上，并兼容现有的J">
<meta property="og:type" content="article">
<meta property="og:title" content="Hexo">
<meta property="og:url" content="https://gitee.com/yuanyongjie/blog.git/2020/08/31/day01/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="scala第一天课堂笔记 0. 大纲 Scala简介  Scala安装验证  Scala IDE  Scala基础知识和语法  Scala控制结构  Scala函数  Scala数组&amp;集合   1. Scala简介   Scala是一门多范式（multi-paradigm）的编程语言，设计初衷是要集成面向对象编程和函数式编程的各种特性。   Scala运行在Java虚拟机上，并兼容现有的J">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572489079814.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572489236844.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572489342550.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572489387728.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572489488133.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/assets%5C1576464214649.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572490315744.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572490338172.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572570960611.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572571025677.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572571084567.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572571244328.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572571323889.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572571457595.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572571501973.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572571593628.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572571744749.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572571779279.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572571795699.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572571970232.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572572050697.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572572268007.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572572308568.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572572361346.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572572481689.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572572537560.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572572551098.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572573085764.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572573109843.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572573128217.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572573257847.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572573307433.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572573360015.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572573418249.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572573480756.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/assets%5C1576465352749.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/assets%5C1576467602003.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572493461288.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/1572508083096.png">
<meta property="og:image" content="https://gitee.com/blog/yuanyongjie/blog/assets%5C1576485465884.png">
<meta property="article:published_time" content="2020-08-31T08:29:23.275Z">
<meta property="article:modified_time" content="2020-08-31T08:41:32.850Z">
<meta property="article:author" content="John Doe">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/blog/yuanyongjie/blog/1572489079814.png">
  
    <link rel="alternate" href="/blog/atom.xml" title="Hexo" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  
<link rel="stylesheet" href="/blog/css/style.css">

<meta name="generator" content="Hexo 5.1.1"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/blog/" id="logo">Hexo</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/blog/">Home</a>
        
          <a class="main-nav-link" href="/blog/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/blog/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="https://gitee.com/yuanyongjie/blog.git"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-day01" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/blog/2020/08/31/day01/" class="article-date">
  <time datetime="2020-08-31T08:29:23.275Z" itemprop="datePublished">2020-08-31</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>scala第一天课堂笔记</p>
<h1 id="0-大纲"><a href="#0-大纲" class="headerlink" title="0. 大纲"></a>0. 大纲</h1><ul>
<li><p>Scala简介</p>
</li>
<li><p>Scala安装验证</p>
</li>
<li><p>Scala IDE</p>
</li>
<li><p>Scala基础知识和语法</p>
</li>
<li><p>Scala控制结构</p>
</li>
<li><p>Scala函数</p>
</li>
<li><p>Scala数组&amp;集合</p>
</li>
</ul>
<h1 id="1-Scala简介"><a href="#1-Scala简介" class="headerlink" title="1. Scala简介"></a>1. Scala简介</h1><p>   Scala是一门多范式（multi-paradigm）的编程语言，设计初衷是要集成面向对象编程和函数式编程的各种特性。<br>   Scala运行在Java虚拟机上，并兼容现有的Java程序。<br>   Scala源代码被编译成Java字节码，所以它可以运行于JVM之上，并可以调用现有的Java类库。<br>   函数编程范式更适合用于Map/Reduce和大数据模型，它摒弃了数据与状态的计算模型，着眼于函数本身，而非执行的过程的数据和状态的处理。函数范式逻辑清晰、简单，非常适合用于处理基于不变数据的批量处理工作，这些工作基本都是通过map和reduce操作转换数据后，生成新的数据副本，然后再进行处理。<br>   像Spark，Flink,kafka等都是采用Scala开发的，所以学习好大数据，掌握scala是必要的。<br>   官网：<a target="_blank" rel="noopener" href="http://scala-lang.org/">http://scala-lang.org/</a> </p>
<h1 id="2-scala安装与验证"><a href="#2-scala安装与验证" class="headerlink" title="2. scala安装与验证"></a>2. scala安装与验证</h1><ul>
<li><p>下载路径</p>
<pre><code> https://www.scala-lang.org/download/2.11.8.html</code></pre>
<p>  <img src="/blog/yuanyongjie/blog/1572489079814.png" alt="1572489079814"></p>
</li>
<li><p>安装</p>
<ul>
<li><p>要求</p>
<p>  不能安装在带有中文或者空格的目录下面，不然会报错，scala命令找不到。</p>
</li>
<li><p>安装</p>
<p>  <img src="/blog/yuanyongjie/blog/1572489236844.png" alt="1572489236844"></p>
</li>
<li><p>jdk必须安装</p>
</li>
<li><p>添加环境变量</p>
<p>  配置SCALA_HOME</p>
<p>  <img src="/blog/yuanyongjie/blog/1572489342550.png" alt="1572489342550"></p>
<p>  添加进path</p>
<p>  <img src="/blog/yuanyongjie/blog/1572489387728.png" alt="1572489387728"></p>
</li>
<li><p>验证</p>
<p>  <img src="/blog/yuanyongjie/blog/1572489488133.png" alt="1572489488133"></p>
<p>  出现上述效果，即scala安装成功。</p>
</li>
</ul>
</li>
</ul>
<h1 id="3-scala的IDE"><a href="#3-scala的IDE" class="headerlink" title="3. scala的IDE"></a>3. scala的IDE</h1><h2 id="3-1-普通的学习开发–Notepad"><a href="#3-1-普通的学习开发–Notepad" class="headerlink" title="3.1. 普通的学习开发–Notepad++"></a>3.1. 普通的学习开发–Notepad++</h2><p>入门案例—-Hello World.</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">	public class HelloWorld &#123;</span></span><br><span class="line"><span class="comment">		public static void main(String[] args) &#123;</span></span><br><span class="line"><span class="comment">			System.out.println(&quot;dddd&quot;);</span></span><br><span class="line"><span class="comment">		&#125;</span></span><br><span class="line"><span class="comment">	&#125;</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="class"><span class="keyword">object</span> <span class="title">HelloWorld</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">main</span></span>(args:<span class="type">Array</span>[<span class="type">String</span>]): <span class="type">Unit</span> = &#123;</span><br><span class="line">		println(<span class="string">&quot;HelloWorld~&quot;</span>)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>编译执行</p>
<blockquote>
<p>E:\work\shenzhen-1902\workspace&gt;scalac HelloWorld.scala</p>
<p>E:\work\shenzhen-1902\workspace&gt;scala HelloWorld<br>HelloWorld~</p>
</blockquote>
<p>现象：</p>
<p><img src="/blog/yuanyongjie/blog/assets%5C1576464214649.png" alt="1576464214649"></p>
<p>​    .java文件经过javac编译之后只会产生一个.class字节码文件，但是.scala文件经过scalac编译之后会产生两个.class文件。</p>
<p>HelloWorld.class</p>
<p><img src="/blog/yuanyongjie/blog/1572490315744.png" alt="1572490315744"></p>
<p>HelloWorld$.class</p>
<p><img src="/blog/yuanyongjie/blog/1572490338172.png" alt="1572490338172"></p>
<p>​    通过反编译软件，我们可以看出来，HelloWorld.scala,在执行的时候需要调用哪个.class,需要调用不带$的.class字节码文件，带$的.class是scala编译之后的文件，不带$的.class是jvm和scala文件运行的纽带。</p>
<h2 id="3-2-高级开发工具–Idea-Eclipse"><a href="#3-2-高级开发工具–Idea-Eclipse" class="headerlink" title="3.2. 高级开发工具–Idea/Eclipse"></a>3.2. 高级开发工具–Idea/Eclipse</h2><h3 id="3-2-1-创建java项目"><a href="#3-2-1-创建java项目" class="headerlink" title="3.2.1. 创建java项目"></a>3.2.1. 创建java项目</h3><ul>
<li>普通java项目</li>
</ul>
<p><img src="/blog/yuanyongjie/blog/1572570960611.png" alt="1572570960611"></p>
<p>​    指定java选项</p>
<p><img src="/blog/yuanyongjie/blog/1572571025677.png" alt="1572571025677"></p>
<p>​    指定项目存储位置：</p>
<p><img src="/blog/yuanyongjie/blog/1572571084567.png" alt="1572571084567"></p>
<p>​    创建的class并运行</p>
<p><img src="/blog/yuanyongjie/blog/1572571244328.png" alt="1572571244328"></p>
<ul>
<li><p>maven项目</p>
<ol>
<li><p>指定maven</p>
<p> 选择settings配置信息</p>
<p> <img src="/blog/yuanyongjie/blog/1572571323889.png" alt="1572571323889"></p>
<p> 配置maven的仓库和配置文件路径</p>
<p> <img src="/blog/yuanyongjie/blog/1572571457595.png" alt="1572571457595"></p>
</li>
<li><p>创建项目</p>
<p> 选中project</p>
<p> <img src="/blog/yuanyongjie/blog/1572571501973.png" alt="1572571501973"></p>
<p> 选中maven的骨架archetype</p>
<p> <img src="/blog/yuanyongjie/blog/1572571593628.png" alt="1572571593628"></p>
<p> 配置maven的坐标</p>
<p> <img src="/blog/yuanyongjie/blog/1572571744749.png" alt="1572571744749"></p>
<p> 选择maven信息</p>
<p> <img src="/blog/yuanyongjie/blog/1572571779279.png" alt="1572571779279"></p>
<p> 项目存储位置</p>
<p> <img src="/blog/yuanyongjie/blog/1572571795699.png" alt="1572571795699"></p>
<p> 新建resources目录，用于存储配置文件</p>
<p> <img src="/blog/yuanyongjie/blog/1572571970232.png" alt="1572571970232"></p>
<p> 需要将resources目录添加到classpath中</p>
<p> <img src="/blog/yuanyongjie/blog/1572572050697.png" alt="1572572050697"></p>
<p> 添加maven依赖,在pom文件中的dependencies中添加</p>
 <figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>mysql<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mysql-connector-java<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>5.1.39<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

</li>
</ol>
</li>
</ul>
<h3 id="3-2-2-创建scala项目"><a href="#3-2-2-创建scala项目" class="headerlink" title="3.2.2. 创建scala项目"></a>3.2.2. 创建scala项目</h3><ul>
<li><p>普通项目的创建</p>
<p>  <img src="/blog/yuanyongjie/blog/1572572268007.png" alt="1572572268007"></p>
<p>  发现没有scala模块</p>
<p>  <img src="/blog/yuanyongjie/blog/1572572308568.png" alt="1572572308568"></p>
<p>  集成scala</p>
<p>  <img src="/blog/yuanyongjie/blog/1572572361346.png" alt="1572572361346"></p>
<p>  选择plugins</p>
<p>  <img src="/blog/yuanyongjie/blog/1572572481689.png" alt="1572572481689"></p>
<p>  插件下载地址：</p>
<p>  ​    <a target="_blank" rel="noopener" href="http://plugins.jetbrains.com/plugin/1347-scala/versions">http://plugins.jetbrains.com/plugin/1347-scala/versions</a></p>
<ol>
<li><p>离线</p>
<p> <img src="/blog/yuanyongjie/blog/1572572537560.png" alt="1572572537560"></p>
<p> 重启idea</p>
<p> <img src="/blog/yuanyongjie/blog/1572572551098.png" alt="1572572551098"></p>
</li>
</ol>
</li>
</ul>
<pre><code>2. 在线

    ![1572572632079](assets/1572572632079.png)

选择scala模块创建

![1572572790572](assets/1572572790572.png)

指定项目位置和scala的sdk

![1572572861775](assets/1572572861775.png)

创建scala的class

![1572572917742](assets/1572572917742.png)

编译并运行

![1572572990109](assets/1572572990109.png)</code></pre>
<ul>
<li><p>maven项目的创建</p>
<p>  指定maven选项卡，不要勾选</p>
<p>  <img src="/blog/yuanyongjie/blog/1572573085764.png" alt="1572573085764"></p>
<p>  指定maven的坐标</p>
<p>  <img src="/blog/yuanyongjie/blog/1572573109843.png" alt="1572573109843"></p>
<p>  项目存储位置</p>
<p>  <img src="/blog/yuanyongjie/blog/1572573128217.png" alt="1572573128217"></p>
<p>  创建class没有scala-class</p>
<p>  <img src="/blog/yuanyongjie/blog/1572573257847.png" alt="1572573257847"></p>
<p>  点击File—&gt;project structure</p>
<p>  <img src="/blog/yuanyongjie/blog/1572573307433.png" alt="1572573307433"></p>
<p>  点击global lib</p>
<p>  <img src="/blog/yuanyongjie/blog/1572573360015.png" alt="1572573360015"></p>
<p>  创建scala-class</p>
<p>  <img src="/blog/yuanyongjie/blog/1572573418249.png" alt="1572573418249"></p>
<p>  编译并执行</p>
<p>  <img src="/blog/yuanyongjie/blog/1572573480756.png" alt="1572573480756"></p>
<p>  scala的maven依赖</p>
  <figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.scala-lang<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>scala-library<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.11.8<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

</li>
</ul>
<h2 id="3-3-scala编码规范"><a href="#3-3-scala编码规范" class="headerlink" title="3.3. scala编码规范"></a>3.3. scala编码规范</h2><ul>
<li><p>命名规划和java一样</p>
<ul>
<li>文件名<ol>
<li>首字母大写</li>
<li>多个单词之间使用驼峰命名</li>
<li>以名词居多</li>
<li>尽量不要使用名词的复数形式</li>
</ol>
</li>
<li>方法函数命名<ol>
<li>首字母小写</li>
<li>多个单词之间使用驼峰命名</li>
<li>以动词+名词</li>
</ol>
</li>
</ul>
</li>
<li><p>文件编码统一为UTF-8</p>
</li>
<li><p>每行缩进使用空格，使用4个空格来代替缩进tab</p>
<p><img src="/blog/yuanyongjie/blog/assets%5C1576465352749.png" alt="1576465352749"></p>
</li>
<li><p>{}的位置写法和java保持一致</p>
</li>
</ul>
<h1 id="4-scala基础知识与语法"><a href="#4-scala基础知识与语法" class="headerlink" title="4. scala基础知识与语法"></a>4. scala基础知识与语法</h1><h2 id="4-1-scala语言的特点"><a href="#4-1-scala语言的特点" class="headerlink" title="4.1. scala语言的特点"></a>4.1. scala语言的特点</h2><p>可拓展<br>  面向对象<br>  函数式编程<br>兼容JAVA<br>  类库调用<br>  互操作<br>语法简洁<br>  代码行短<br>  类型推断<br>  抽象控制<br>静态类型化<br>  可检验<br>  安全重构<br>支持并发控制<br>  强计算能力<br>  自定义其他控制结构</p>
<h2 id="4-2-scala与java的关系"><a href="#4-2-scala与java的关系" class="headerlink" title="4.2. scala与java的关系"></a>4.2. scala与java的关系</h2><p>1、都是基于JVM虚拟机运行的<br>   Scala编译之后的文件也是.class，都要转换为字节码，然后运行在JVM虚拟机之上。<br>2、Scala和Java相互调用<br>   在Scala中可以直接调用Java的代码，同时在Java中也可以直接调用Scala的代码<br>3、Java 8 VS Scala<br>   1）Java 8（lambda）没有出来之前，Java只是面向对象的一门语言，但是Java 8出来以后，Java就是一个面向对象和面向函数的混合语言了。<br>   2）首先我们要对Scala进行精确定位，从某种程度上讲，Scala并不是一个纯粹的面向函数的编程语言，有人认为 Scala是一个带有闭包的静态面向对象语言），更准确地说，Scala是面向函数与面向对象的混合。<br>   3）Scala设计的初衷是面向函数FP，而Java起家是面向对象OO，现在两者都是OO和FP的混合语言，是否可以这么认为：Scala = FP + OO，而Java = OO+ FP？<br>   由于面向对象OO和面向函数FP两种范式是类似横坐标和纵坐标的两者不同坐标方向的思考方式，类似数据库和对象之间的不匹配阻抗关系，两者如果结合得不好恐怕就不会产生1+1&gt;2的效果。<br>   面向对象是最接近人类思维的方式，而面向函数是最接近计算机的思维方式。如果你想让计算机为人的业务建模服务，那么以OO为主；如果你希望让计算机能自己通过算法从大数据中自动建模，那么以FP为主。所以，Java可能还会在企业工程类软件中占主要市场，而Scala则会在科学计算大数据分析等领域抢占Java市场，比如Scala的Spark大有替代Java的Hadoop之趋势。</p>
<h2 id="4-3-Scala解释器"><a href="#4-3-Scala解释器" class="headerlink" title="4.3. Scala解释器"></a>4.3. Scala解释器</h2><p>1、Scala解释器读到一个表达式，对它进行求值，将它打印出来，接着再继续读下一个表达式。这个过程被称做读取read–求值eval–打印print–循环loop，即：<strong>REPL</strong>。<br>   从技术上讲，scala程序并不是一个解释器。实际发生的是，你输入的内容被快速地编译成字节码，然后这段字节码交由Java虚拟机执行。正因为如此，大多数scala程序员更倾向于将它称做“REPL”</p>
<p><img src="/blog/yuanyongjie/blog/assets%5C1576467602003.png" alt="1576467602003"></p>
<h2 id="4-4-scala变量的定义"><a href="#4-4-scala变量的定义" class="headerlink" title="4.4. scala变量的定义"></a>4.4. scala变量的定义</h2><p>​    scala的变量定义分为两种方式，分别需要使用关键字val和var。</p>
<ul>
<li><p>val</p>
<p>  val a = 3</p>
</li>
<li><p>var</p>
<p>  var a = 3</p>
<p>  ​    val和var都可以用来定义变量，唯一的区别就在于，val定义的变量是不可变，而var定义的变量是可变的。不可变的量确实类似常量（被final修饰的变量），但不叫常量，只能叫不可变量的量。</p>
<p>  ​    在今后的开发过程中，能使用val就使用val，var尽量不用，因为scala编程的特点，是在创建变量的时候可以省略数据类型，val有助于进行类型的推断。var在操作过程中不利于变量的类型。</p>
  <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">    scala&gt; <span class="keyword">var</span> a = <span class="number">3</span></span><br><span class="line">    a: <span class="type">Int</span> = <span class="number">3</span></span><br><span class="line">    scala&gt; <span class="keyword">val</span> b = <span class="number">4</span></span><br><span class="line">    b: <span class="type">Int</span> = <span class="number">4</span></span><br><span class="line">    scala&gt; <span class="keyword">var</span> str = <span class="string">&quot;abcdefg&quot;</span></span><br><span class="line">    str: <span class="type">String</span> = abcdefg</span><br><span class="line">    scala&gt; <span class="keyword">var</span> h:<span class="type">String</span> = <span class="string">&quot;hehe&quot;</span></span><br><span class="line">h: <span class="type">String</span> = hehe</span><br><span class="line">    scala&gt; a = a + <span class="number">1</span></span><br><span class="line">a: <span class="type">Int</span> = <span class="number">4</span></span><br><span class="line">    scala&gt; println(a)</span><br><span class="line"><span class="number">4</span></span><br><span class="line">    scala&gt; b = b + <span class="number">1</span></span><br><span class="line">    &lt;console&gt;:<span class="number">12</span>: error: reassignment to <span class="keyword">val</span></span><br><span class="line">           b = b + <span class="number">1</span></span><br></pre></td></tr></table></figure>

<p>  一个完整的变量的定义如下：</p>
<blockquote>
<p>val a:Int = 3</p>
</blockquote>
<p>  其中val为变量修饰符，a为变量名，Int为a的数据类型，其中需要将变量名和数据类型使用:连接，=右侧为变量的值。</p>
</li>
</ul>
<h2 id="4-5-scala的数据类型"><a href="#4-5-scala的数据类型" class="headerlink" title="4.5. scala的数据类型"></a>4.5. scala的数据类型</h2><p><img src="/blog/yuanyongjie/blog/1572493461288.png" alt="1572493461288"></p>
<p>说明：scala拥有和java一样的数据类型，和java的数据类型的内存布局完全一致，精度也完全一致。需要说明一点的是Any和AnyRef，其中Any是对象的超类（运行时的一个概念，比如 val p = new Person() ，引用p指向的对象有一个父类Any），AnyRef是类的超类(class Person{}, 该类Person有一个隐含的超类AnyRef)，实例/对象是类的具体化。</p>
<h2 id="4-6-scala操作符说明"><a href="#4-6-scala操作符说明" class="headerlink" title="4.6. scala操作符说明"></a>4.6. scala操作符说明</h2><p>scala的操作符合java一模一样：略。</p>
<ol>
<li><p>在scala调用一些方法或者函数的时候，如果方法或者函数是空参的，可以省略掉().</p>
</li>
<li><p>在scala中一行表示的结尾不像java需要使用”;”，scala可以省略</p>
</li>
</ol>
<h1 id="5-scala的流程控制结构"><a href="#5-scala的流程控制结构" class="headerlink" title="5. scala的流程控制结构"></a>5. scala的流程控制结构</h1><h2 id="5-1-if表达式"><a href="#5-1-if表达式" class="headerlink" title="5.1. if表达式"></a>5.1. if表达式</h2><p>​    scala中的if表达式，基本和java中的if表达式一模一样，唯一的区别就是scala中的if、if-else、if-elseif-else有返回值！</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">scala&gt; <span class="keyword">val</span> age = <span class="number">18</span></span><br><span class="line">age: <span class="type">Int</span> = <span class="number">18</span></span><br><span class="line"></span><br><span class="line">scala&gt; <span class="keyword">if</span>(age &gt; <span class="number">16</span>) <span class="string">&quot;adult&quot;</span> <span class="keyword">else</span> <span class="string">&quot;child&quot;</span></span><br><span class="line">res17: <span class="type">String</span> = adult</span><br><span class="line"></span><br><span class="line">scala&gt; <span class="keyword">val</span> ret = <span class="keyword">if</span>(age &gt; <span class="number">16</span>) <span class="string">&quot;adult&quot;</span> <span class="keyword">else</span> <span class="string">&quot;child&quot;</span></span><br><span class="line">ret: <span class="type">String</span> = adult</span><br><span class="line"></span><br><span class="line">scala&gt; println(<span class="string">&quot;ret = &quot;</span> + ret)</span><br><span class="line">ret = adult</span><br><span class="line"></span><br><span class="line">scala&gt; <span class="keyword">var</span> result = <span class="string">&quot;&quot;</span></span><br><span class="line">result: <span class="type">String</span> = <span class="string">&quot;&quot;</span></span><br><span class="line"></span><br><span class="line">scala&gt; <span class="keyword">if</span>(age &gt; <span class="number">16</span>) result = <span class="string">&quot;adult&quot;</span> <span class="keyword">else</span> result = <span class="string">&quot;child&quot;</span></span><br><span class="line"></span><br><span class="line">scala&gt; println(<span class="string">&quot;result= &quot;</span> + result)</span><br><span class="line">result= adult</span><br><span class="line"></span><br><span class="line">scala&gt; <span class="keyword">if</span>(age &gt; <span class="number">16</span>) <span class="string">&quot;adult&quot;</span> <span class="keyword">else</span> <span class="number">123</span></span><br><span class="line">res21: <span class="type">Any</span> = adult</span><br></pre></td></tr></table></figure>

<p>​    记住：scala中任意的表达式，都有返回值。</p>
<p>如果else丢失了<br>   if（x&gt;0） 1<br>  那么有可能if语句没有输出值，但是在Scala中，每个表达式都有值，这个问题的解决方案是引入一个Unit类，写作(),不带else语句的if语句等同于if(x&gt;0) 1 else ()</p>
<p>​    scala的返回值可以省略return关键字，表达式的最后一句话，作为表达式的返回值返回。return关键字通常使用在函数中进行逻辑的终止，比如循环。</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> f = <span class="number">3</span></span><br><span class="line"><span class="keyword">var</span> n = <span class="number">10</span></span><br><span class="line"><span class="keyword">var</span> m = <span class="number">1</span></span><br><span class="line"><span class="keyword">val</span> d = <span class="keyword">if</span>(n &lt; <span class="number">18</span>)&#123;f = f + n ; m = m +n ; f+m&#125;</span><br><span class="line"></span><br><span class="line">===&gt; d=<span class="number">24</span></span><br></pre></td></tr></table></figure>

<p>注意：前面提到过，scala中的语句终止就是换行，也就是一行一个语句，此时便可以省略”;”，但是当一行有多条语句的时候，就应该使用”;”分隔。在表达式块中同样可以使用换行作为一条语句的分隔。</p>
<p>​    如果if/循环{}中只有一条语句，是可以省略{}，但是如果大家查看过阿里巴巴编程规范中话，其建议哪怕只有一条语句也写上{}，会显得结构很清晰。</p>
<h2 id="5-2-循环"><a href="#5-2-循环" class="headerlink" title="5.2. 循环"></a>5.2. 循环</h2><h3 id="5-2-1-while"><a href="#5-2-1-while" class="headerlink" title="5.2.1. while"></a>5.2.1. while</h3><figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">  * while循环操作</span></span><br><span class="line"><span class="comment">  *     1+...+10</span></span><br><span class="line"><span class="comment">  *    int sum = 0;</span></span><br><span class="line"><span class="comment">  *    int n = 1;</span></span><br><span class="line"><span class="comment">  *    while(n &lt;= 10) &#123;</span></span><br><span class="line"><span class="comment">  *      sum += n;</span></span><br><span class="line"><span class="comment">  *      n++</span></span><br><span class="line"><span class="comment">  *    &#125;</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"><span class="class"><span class="keyword">object</span> <span class="title">_01WhileLoopDemo</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">main</span></span>(args: <span class="type">Array</span>[<span class="type">String</span>]): <span class="type">Unit</span> = &#123;</span><br><span class="line">		<span class="keyword">var</span> sum = <span class="number">0</span></span><br><span class="line">		<span class="keyword">var</span> n = <span class="number">1</span></span><br><span class="line">		<span class="keyword">while</span>(n &lt;= <span class="number">10</span>) &#123;</span><br><span class="line">			sum += n</span><br><span class="line">			<span class="comment">//++/--自增/自减运算符在scala中不支持，因为已经被scala集合的对应函数所占据了</span></span><br><span class="line"><span class="comment">//			n++</span></span><br><span class="line">			n += <span class="number">1</span></span><br><span class="line">		&#125;</span><br><span class="line">		println(<span class="string">&quot;sum = &quot;</span> + sum)</span><br><span class="line"></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>注意：error: value ++/– is not a member of Int</p>
<p>​    scala中不能直接对一个变量执行自增/减，++/–是scala集合的一个函数。</p>
<h3 id="5-2-2-do-while"><a href="#5-2-2-do-while" class="headerlink" title="5.2.2 do while"></a>5.2.2 do while</h3><figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">  * do while循环操作</span></span><br><span class="line"><span class="comment">  *     1+...+10</span></span><br><span class="line"><span class="comment">  *    int sum = 0;</span></span><br><span class="line"><span class="comment">  *    int n = 1;</span></span><br><span class="line"><span class="comment">  *    do &#123;</span></span><br><span class="line"><span class="comment">  *      sum += n;</span></span><br><span class="line"><span class="comment">  *      n++;</span></span><br><span class="line"><span class="comment">  *    &#125; while(n &lt;= 10)</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"><span class="class"><span class="keyword">object</span> <span class="title">_02DoWhileLoopDemo</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">main</span></span>(args: <span class="type">Array</span>[<span class="type">String</span>]): <span class="type">Unit</span> = &#123;</span><br><span class="line">		<span class="keyword">var</span> sum = <span class="number">0</span></span><br><span class="line">		<span class="keyword">var</span> n = <span class="number">1</span></span><br><span class="line">		do &#123;</span><br><span class="line">			sum += n</span><br><span class="line">			n += <span class="number">1</span></span><br><span class="line">		&#125; <span class="keyword">while</span> (n &lt;= <span class="number">10</span>)</span><br><span class="line">		println(<span class="string">&quot;sum = &quot;</span> + sum)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="5-2-3-循环练习"><a href="#5-2-3-循环练习" class="headerlink" title="5.2.3. 循环练习"></a>5.2.3. 循环练习</h3><p>​    登录用户名密码的游戏：三次机会，从控制台输入用户名密码，如果成功登录，返回登录成功，失败，则反馈错误信息！</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">object</span> <span class="title">_03WhileLoopTest</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">main</span></span>(args: <span class="type">Array</span>[<span class="type">String</span>]): <span class="type">Unit</span> = &#123;</span><br><span class="line">		<span class="comment">//从控制台输入使用readLine()已经过时</span></span><br><span class="line"><span class="comment">//		readLine()//StdIn.readLine</span></span><br><span class="line">		<span class="keyword">val</span> dbUser = <span class="string">&quot;pgone&quot;</span></span><br><span class="line">		<span class="keyword">val</span> dbPwd = <span class="string">&quot;lxl&quot;</span></span><br><span class="line">		<span class="keyword">var</span> count = <span class="number">3</span></span><br><span class="line">		<span class="keyword">while</span>(count &gt; <span class="number">0</span>) &#123;</span><br><span class="line">			count -= <span class="number">1</span></span><br><span class="line">			<span class="keyword">val</span> username = <span class="type">StdIn</span>.readLine(<span class="string">&quot;请输入您的用户名：&quot;</span>)</span><br><span class="line">			<span class="keyword">val</span> pwd = <span class="type">StdIn</span>.readLine(<span class="string">&quot;请输入您的密码：&quot;</span>)</span><br><span class="line">			<span class="keyword">if</span> (dbUser == username &amp;&amp; dbPwd == pwd) &#123;</span><br><span class="line">				println(<span class="string">&quot;欢迎&quot;</span> + username + <span class="string">&quot;登录xxx官网~&quot;</span>)</span><br><span class="line">				count = <span class="number">-1</span></span><br><span class="line">                <span class="comment">//return</span></span><br><span class="line">			&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">				println(<span class="string">&quot;用户名或密码有误，请重试,还有&quot;</span> + count + <span class="string">&quot;次机会~&quot;</span>)</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="5-3-循环的终止"><a href="#5-3-循环的终止" class="headerlink" title="5.3. 循环的终止"></a>5.3. 循环的终止</h2><p>​    在java中终止循环有关键字，continue,break,return,但是在scala中没有前两者continue和break。该如何终止循环呢？</p>
<p>​    有三种方式来结束循环：</p>
<ol>
<li>使用return语句来控制循环结束</li>
<li>使用循环结束的条件来进行控制，比如上例中的count &gt;= 0</li>
<li>还可以使用breakable函数体来进行控制</li>
</ol>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> scala.util.control.<span class="type">Breaks</span>._</span><br><span class="line"><span class="class"><span class="keyword">object</span> <span class="title">_03WhileLoopTest</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">main</span></span>(args: <span class="type">Array</span>[<span class="type">String</span>]): <span class="type">Unit</span> = &#123;</span><br><span class="line">		<span class="keyword">val</span> dbUser = <span class="string">&quot;pgone&quot;</span></span><br><span class="line">		<span class="keyword">val</span> dbPwd = <span class="string">&quot;lxl&quot;</span></span><br><span class="line">		<span class="keyword">var</span> count = <span class="number">3</span></span><br><span class="line"></span><br><span class="line">		breakable &#123;</span><br><span class="line">			<span class="keyword">while</span>(count &gt; <span class="number">0</span>) &#123;</span><br><span class="line">				count -= <span class="number">1</span></span><br><span class="line">				<span class="keyword">val</span> username = <span class="type">StdIn</span>.readLine(<span class="string">&quot;请输入您的用户名：&quot;</span>)</span><br><span class="line">				<span class="keyword">val</span> pwd = <span class="type">StdIn</span>.readLine(<span class="string">&quot;请输入您的密码：&quot;</span>)</span><br><span class="line">				<span class="keyword">if</span> (dbUser == username &amp;&amp; dbPwd == pwd) &#123;</span><br><span class="line">					println(<span class="string">&quot;欢迎&quot;</span> + username + <span class="string">&quot;登录xxx官网~&quot;</span>)</span><br><span class="line">					<span class="keyword">break</span></span><br><span class="line">				&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">					println(<span class="string">&quot;用户名或密码有误，请重试,还有&quot;</span> + count + <span class="string">&quot;次机会~&quot;</span>)</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="5-4-for循环"><a href="#5-4-for循环" class="headerlink" title="5.4. for循环"></a>5.4. for循环</h2><h3 id="5-4-1-for循环"><a href="#5-4-1-for循环" class="headerlink" title="5.4.1. for循环"></a>5.4.1. for循环</h3><p>​    在java中有2中写法，普通的for循环for(变量;条件;自增或自减){循环体} or for(类型 变量 : 集合) {}。</p>
<p>​    scala中的for循环该如何定义呢？</p>
<p>​    scala中并没有像java中普通for循环的语法结构，更像是高级for循环。</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (变量 &lt;- 集合) &#123;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​    将上述的while循环使用for循环改写</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">	java的for循环</span></span><br><span class="line"><span class="comment">	for(int a = 0初始化①; a &lt; 10条件判断②; a++变量改变③) &#123;</span></span><br><span class="line"><span class="comment">		//循环体</span></span><br><span class="line"><span class="comment">		业务逻辑④</span></span><br><span class="line"><span class="comment">	&#125;</span></span><br><span class="line"><span class="comment">	1-&gt;2-&gt;4-&gt;3-&gt;2-&gt;4-&gt;3...</span></span><br><span class="line"><span class="comment">	高级for循环foreach</span></span><br><span class="line"><span class="comment">	for(类型 变量 : 集合) &#123;</span></span><br><span class="line"><span class="comment">		xxxx</span></span><br><span class="line"><span class="comment">	&#125;</span></span><br><span class="line"><span class="comment">	scala中没有像java中的第一种for循环，scala中的for循环，有点类似java中的高级for循环，</span></span><br><span class="line"><span class="comment">	结构如下：</span></span><br><span class="line"><span class="comment">	for(变量 &lt;- 集合) &#123;</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">	&#125;</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">object</span> <span class="title">_04ForLoopDemo</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">main</span></span>(args: <span class="type">Array</span>[<span class="type">String</span>]): <span class="type">Unit</span> = &#123;</span><br><span class="line">		<span class="comment">/*</span></span><br><span class="line"><span class="comment">			将前面的while循环案例适用for循环实现</span></span><br><span class="line"><span class="comment">			scala中生成一个集合可以使用整型变量 to/until 数字</span></span><br><span class="line"><span class="comment">			会生成一个返回</span></span><br><span class="line"><span class="comment">			to: 1 to 5/1.to(5) 包含</span></span><br><span class="line"><span class="comment">				scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5)</span></span><br><span class="line"><span class="comment">			until: 1 until 5/1.until(5) 不包含</span></span><br><span class="line"><span class="comment">				scala.collection.immutable.Range = Range(1, 2, 3, 4)</span></span><br><span class="line"><span class="comment">		 */</span></span><br><span class="line">		<span class="keyword">val</span> range = <span class="number">1.</span>to(<span class="number">10</span>)</span><br><span class="line">		<span class="keyword">var</span> sum = <span class="number">0</span></span><br><span class="line">		<span class="keyword">for</span>(n &lt;- range) &#123;</span><br><span class="line">			sum += n</span><br><span class="line">		&#125;</span><br><span class="line">		println(<span class="string">&quot;sum = &quot;</span> + sum)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>说明：添加reverse主要就是向进行循环的反转</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">val</span> range = <span class="number">1.</span>to(<span class="number">10</span>)</span><br><span class="line"><span class="keyword">var</span> sum = <span class="number">0</span></span><br><span class="line"><span class="keyword">for</span>(n &lt;- range reverse) &#123;</span><br><span class="line">    println(<span class="string">&quot;n=&quot;</span> + n)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>n=10<br>n=9<br>n=8<br>n=7<br>n=6<br>n=5<br>n=4<br>n=3<br>n=2<br>n=1</p>
</blockquote>
<h3 id="5-4-2-循环的嵌套"><a href="#5-4-2-循环的嵌套" class="headerlink" title="5.4.2. 循环的嵌套"></a>5.4.2. 循环的嵌套</h3><figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">	循环的嵌套</span></span><br><span class="line"><span class="comment">	打印矩阵</span></span><br><span class="line"><span class="comment">	*****</span></span><br><span class="line"><span class="comment">	*****</span></span><br><span class="line"><span class="comment">	*****</span></span><br><span class="line"><span class="comment">	3行 * 5列</span></span><br><span class="line"><span class="comment">	循环的嵌套中：外循环控制行，内循环控制每一行对应的列</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">object</span> <span class="title">_05LoopNestDemo</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">main</span></span>(args: <span class="type">Array</span>[<span class="type">String</span>]): <span class="type">Unit</span> = &#123;</span><br><span class="line">		<span class="keyword">for</span>(i &lt;- <span class="number">1</span> to <span class="number">3</span>) &#123;</span><br><span class="line">			<span class="keyword">for</span>(j &lt;- <span class="number">1</span> to <span class="number">5</span>) &#123;</span><br><span class="line">				print(<span class="string">&quot;*&quot;</span>)</span><br><span class="line">			&#125;</span><br><span class="line">			println</span><br><span class="line">		&#125;</span><br><span class="line">		println(<span class="string">&quot;----------打印一个三角形-------------&quot;</span>)</span><br><span class="line">		<span class="keyword">for</span>(i &lt;- <span class="number">1</span> to <span class="number">5</span>) &#123;</span><br><span class="line">			<span class="keyword">for</span>(j &lt;- <span class="number">1</span> to <span class="number">5</span>) &#123;</span><br><span class="line">				<span class="keyword">if</span>(j &lt;= i)</span><br><span class="line">					print(<span class="string">&quot;*&quot;</span>)</span><br><span class="line">			&#125;</span><br><span class="line">			println</span><br><span class="line">		&#125;</span><br><span class="line">		println(<span class="string">&quot;----------改写打印一个三角形-------------&quot;</span>)</span><br><span class="line">		<span class="keyword">for</span>(i &lt;- <span class="number">1</span> to <span class="number">5</span>) &#123;</span><br><span class="line">			<span class="keyword">for</span>(j &lt;- <span class="number">1</span> to i) &#123;</span><br><span class="line">				print(<span class="string">&quot;*&quot;</span>)</span><br><span class="line">			&#125;</span><br><span class="line">			println</span><br><span class="line">		&#125;</span><br><span class="line">		println(<span class="string">&quot;----------改写打印一个三角形-------------&quot;</span>)</span><br><span class="line">		<span class="keyword">for</span>(i &lt;- <span class="number">1</span> to <span class="number">5</span>) &#123;</span><br><span class="line">			<span class="keyword">for</span>(j &lt;- i to <span class="number">5</span>) &#123;</span><br><span class="line">				print(<span class="string">&quot;*&quot;</span>)</span><br><span class="line">			&#125;</span><br><span class="line">			println</span><br><span class="line">		&#125;</span><br><span class="line">		println(<span class="string">&quot;----------scala for嵌套写法-------------&quot;</span>)</span><br><span class="line">		<span class="keyword">for</span>(i &lt;- <span class="number">1</span> to <span class="number">5</span>; j &lt;- <span class="number">1</span> to i) &#123;</span><br><span class="line">			print(<span class="string">&quot;*&quot;</span>)</span><br><span class="line">			<span class="keyword">if</span>(i == j) &#123;</span><br><span class="line">				println</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		println(<span class="string">&quot;----------scala for嵌套写法-------------&quot;</span>)</span><br><span class="line">		<span class="keyword">for</span>(i &lt;- <span class="number">1</span> to <span class="number">5</span>; j &lt;- <span class="number">1</span> to <span class="number">5</span>; <span class="keyword">if</span> j &lt;= i) &#123;</span><br><span class="line">			print(<span class="string">&quot;*&quot;</span>)</span><br><span class="line">			<span class="keyword">if</span>(i == j) &#123;</span><br><span class="line">				println</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>练习题：9*9乘法口诀表。</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">object</span> <span class="title">_06LoopTest</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">main</span></span>(args: <span class="type">Array</span>[<span class="type">String</span>]): <span class="type">Unit</span> = &#123;</span><br><span class="line">		<span class="keyword">for</span>(i &lt;- <span class="number">1</span> to <span class="number">9</span>; j &lt;- <span class="number">1</span> to <span class="number">9</span>; <span class="keyword">if</span> j &lt;= i) &#123;</span><br><span class="line"><span class="comment">//			print(j + &quot;*&quot; + i + &quot;=&quot; + (i * j) + &quot;\t&quot;)</span></span><br><span class="line">			print(<span class="string">s&quot;<span class="subst">$&#123;j&#125;</span>*<span class="subst">$&#123;i&#125;</span>=<span class="subst">$&#123;i * j&#125;</span>\t&quot;</span>)</span><br><span class="line">			<span class="keyword">if</span>(i == j) &#123;</span><br><span class="line">				println</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="5-5-异常控制"><a href="#5-5-异常控制" class="headerlink" title="5.5. 异常控制"></a>5.5. 异常控制</h2><p>​    scala的异常体系，在很大程度上沿用java的异常体系的，只不过在书写结构上略有差异。</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">  * scala异常控制</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"><span class="class"><span class="keyword">object</span> <span class="title">_07ExceptionDemo</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">main</span></span>(args: <span class="type">Array</span>[<span class="type">String</span>]): <span class="type">Unit</span> = &#123;</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line"><span class="comment">//			var i = 1 / 0</span></span><br><span class="line">			<span class="comment">//lazy 懒加载 或者延迟加载 被lazy所修饰的变量，之后再第一次被调用的时候才会进行初始化</span></span><br><span class="line">			<span class="keyword">lazy</span> <span class="keyword">val</span> num = <span class="type">Integer</span>.valueOf(<span class="string">&quot;abcd&quot;</span>)</span><br><span class="line"><span class="comment">//			println(num)</span></span><br><span class="line"><span class="comment">//			val file = new FileInputStream(&quot;abedefg&quot;)</span></span><br><span class="line">		&#125; <span class="keyword">catch</span> &#123;</span><br><span class="line">			<span class="keyword">case</span> e: <span class="type">ArithmeticException</span> =&gt; &#123;</span><br><span class="line">				println(e.getMessage)</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">case</span> e1: <span class="type">NumberFormatException</span> =&gt; &#123;</span><br><span class="line"><span class="comment">//				println(e1.getMessage)</span></span><br><span class="line">				e1.printStackTrace()</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">case</span> _:<span class="type">Exception</span> =&gt; &#123;<span class="comment">//_下划线代表上述没有匹配到的其他的异常</span></span><br><span class="line">				println(<span class="string">&quot;文件找不到&quot;</span>)</span><br><span class="line"><span class="comment">//				throw new RuntimeException(&quot;RuntimeException&quot;)</span></span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​    上述代码，在执行过程中出现异常：</p>
<blockquote>
<p>java.lang.ArithmeticException: / by zero</p>
</blockquote>
<p>​    在java中学习了两种异常的处理方式：throws和try-catch。throws和java中的一模一样，将异常转交给调用者进行处理。try-catch则意味着自己要进行处理，但是编写的方式和java不一样。</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">case</span> e: <span class="type">ArithmeticException</span> =&gt; &#123;</span><br><span class="line">    println(e.getMessage)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>说明：上面的案例中，更进一步的学习了一个关键字lazy(懒加载)，被lazy所修饰的变量，只有当第一次被使用的时候才会进行初始化，没有使用之前只是记录了存在，检查语法结构是否正确。可以节省一定的资源空间。</p>
<h1 id="6-scala的函数"><a href="#6-scala的函数" class="headerlink" title="6. scala的函数"></a>6. scala的函数</h1><h2 id="6-1-函数的定义"><a href="#6-1-函数的定义" class="headerlink" title="6.1. 函数的定义"></a>6.1. 函数的定义</h2><p>​     Scala除了方法外还支持函数。方法对对象进行操作，函数不是。要定义函数，你需要给出函数的名称、参数和函数体，就像这样：</p>
<p><img src="/blog/yuanyongjie/blog/1572508083096.png" alt="1572508083096"></p>
<p>1、你必须给出所有参数的类型。不过，只要函数不是递归的，你就不需要指定返回类型。Scala编译器可以通过=符号右侧的表达式的类型推断出返回类型。<br>2、“=”并不只是用来分割函数签名和函数体的，它的另一个作用是告诉编译器是否对函数的返回值进行类型推断！如果省去=,则认为函数是没有返回值的！</p>
<p>3、在scala中一个函数的最后一句话就是该函数的返回值，不需要使用return，当然加上也行。</p>
<h2 id="6-2-函数定义练习"><a href="#6-2-函数定义练习" class="headerlink" title="6.2. 函数定义练习"></a>6.2. 函数定义练习</h2><figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">object</span> <span class="title">_08FunctionOps</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">main</span></span>(args: <span class="type">Array</span>[<span class="type">String</span>]): <span class="type">Unit</span> = &#123;</span><br><span class="line"><span class="comment">//		show()</span></span><br><span class="line">		<span class="keyword">val</span> ret = sayHi(<span class="string">&quot;雷德言&quot;</span>)</span><br><span class="line">		println(ret)</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">show</span></span>() = &#123;</span><br><span class="line">		println(<span class="string">&quot;abcde&quot;</span>)</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">sayHi</span></span>(name:<span class="type">String</span>) = &#123;</span><br><span class="line">		<span class="string">&quot;Nice to meet you, &quot;</span> + name</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>说明：函数可以不使用return语句，但是如果加上return，那返回值类型，必须要加上，否则：</p>
<p><img src="/blog/yuanyongjie/blog/assets%5C1576485465884.png" alt="1576485465884"></p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">sayHi</span></span>(name:<span class="type">String</span>):<span class="type">String</span> = &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;Nice to meet you, &quot;</span> + name</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="6-3-特殊函数"><a href="#6-3-特殊函数" class="headerlink" title="6.3. 特殊函数"></a>6.3. 特殊函数</h2><ul>
<li><p>单行函数</p>
<p>  所谓单行函数，指的是函数体只有一行的函数。</p>
<blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">def sayHello(name:String) &#x3D; println(&quot;Nice to meet you, &quot; + name)</span><br></pre></td></tr></table></figure>
</blockquote>
<p>  注意：单行函数，必须要使用”=”来做函数的返回值类型推断。</p>
</li>
<li><p>无参函数</p>
<pre><code>函数的参数列表为空。</code></pre>
  <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">show</span></span>() = &#123;</span><br><span class="line">    println(<span class="string">&quot;abcde&quot;</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>  注意：定义空参函数的时候，如果函数加了()，在调用的时候，()可以省略；但是如果在定义的时候没有加()，在调用的时候，也只能省略，不能加()。</p>
</li>
<li><p>递归函数</p>
<p>  ​    在特定条件下，函数调用本身。</p>
<p>  阶乘求解：5!</p>
  <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">	  * 阶乘</span></span><br><span class="line"><span class="comment">	  * n!= n * (n-1)*..*2*1</span></span><br><span class="line"><span class="comment">	  * n!= n * (n-1)!</span></span><br><span class="line"><span class="comment">	  * 1！ = 1</span></span><br><span class="line"><span class="comment">	  */</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">factorial</span></span>(n:<span class="type">Int</span>):<span class="type">Int</span> = &#123;</span><br><span class="line">    <span class="keyword">if</span>(n == <span class="number">1</span>)</span><br><span class="line">    <span class="number">1</span></span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">    n * factorial(n - <span class="number">1</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h2 id="6-4-函数参数的特点"><a href="#6-4-函数参数的特点" class="headerlink" title="6.4. 函数参数的特点"></a>6.4. 函数参数的特点</h2><h3 id="6-4-1-默认参数和带名参数"><a href="#6-4-1-默认参数和带名参数" class="headerlink" title="6.4.1. 默认参数和带名参数"></a>6.4.1. 默认参数和带名参数</h3><figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span></span>(args: <span class="type">Array</span>[<span class="type">String</span>]): <span class="type">Unit</span> = &#123;</span><br><span class="line">    showAddr(<span class="string">&quot;赖春明&quot;</span>, <span class="number">1688888168</span>, <span class="string">&quot;广西&quot;</span>, <span class="string">&quot;CRP&quot;</span>)<span class="comment">//会覆盖默认值</span></span><br><span class="line">    showAddr(<span class="string">&quot;黄若洋&quot;</span>, <span class="number">1381638338</span>, <span class="string">&quot;广东&quot;</span>)<span class="comment">//使用默认值</span></span><br><span class="line">    <span class="comment">//传递参数的时候，可以指定具体的参数名称</span></span><br><span class="line">    showAddr(phone = <span class="number">1395959599</span>L, name = <span class="string">&quot;zhangsan&quot;</span>, province = <span class="string">&quot;lisi&quot;</span>)</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">showAddr</span></span>(name:<span class="type">String</span>, phone:<span class="type">Long</span>, province:<span class="type">String</span>, country:<span class="type">String</span> = <span class="string">&quot;CHINA&quot;</span>): <span class="type">Unit</span> = &#123;</span><br><span class="line">    println(<span class="string">s&quot;name=<span class="subst">$name</span>, phone=<span class="subst">$phone</span>, province=<span class="subst">$province</span>, country=<span class="subst">$country</span>&quot;</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>scala的函数参数列表，在定义的时候，可以使用有默认值的参数，在做函数调用的时候可以使用带名的参数，所以有时我们是无法通过函数传递的参数来推断出具体的参数列表顺序。</p>
<h3 id="6-4-2-可变参数"><a href="#6-4-2-可变参数" class="headerlink" title="6.4.2. 可变参数"></a>6.4.2. 可变参数</h3><p>java版本的可变参数</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">VariableParamOps</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Calc calc = <span class="keyword">new</span> Calc();</span><br><span class="line">        System.out.println(calc.add(<span class="number">1</span>, <span class="number">3</span>));</span><br><span class="line">        System.out.println(calc.add(<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>));</span><br><span class="line">        System.out.println(calc.add(<span class="keyword">new</span> <span class="keyword">int</span>[]&#123;<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">7</span>&#125;));</span><br><span class="line">        System.out.println(calc.add(<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">7</span>, <span class="number">9</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Calc</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">add</span><span class="params">(<span class="keyword">int</span> a, <span class="keyword">int</span> b)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> a + b;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">add</span><span class="params">(<span class="keyword">int</span> a, <span class="keyword">int</span> b, <span class="keyword">int</span> c)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> a + b + c;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//数组</span></span><br><span class="line"><span class="comment">//    public int add(int[] arr) &#123;</span></span><br><span class="line"><span class="comment">//        int sum = 0;</span></span><br><span class="line"><span class="comment">//        for(int i : arr) &#123;</span></span><br><span class="line"><span class="comment">//            sum += i;</span></span><br><span class="line"><span class="comment">//        &#125;</span></span><br><span class="line"><span class="comment">//        return sum;</span></span><br><span class="line"><span class="comment">//    &#125;</span></span><br><span class="line">    <span class="comment">//可变参数</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">add</span><span class="params">(<span class="keyword">int</span> ... arr)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> sum = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i : arr) &#123;</span><br><span class="line">            sum += i;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> sum;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>scala版本</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//scala中的可变参数</span></span><br><span class="line"><span class="class"><span class="keyword">object</span> <span class="title">_11FunctionDemo</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">main</span></span>(args: <span class="type">Array</span>[<span class="type">String</span>]): <span class="type">Unit</span> = &#123;</span><br><span class="line">		println(add(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>))</span><br><span class="line">		println(add(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">5</span>))</span><br><span class="line">		<span class="comment">//声明scala中的一个数组</span></span><br><span class="line">		<span class="keyword">val</span> a = <span class="type">Array</span>(<span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>)</span><br><span class="line">		println(add(a: _*))</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">add</span></span>(arr: <span class="type">Int</span>*) = &#123;</span><br><span class="line">		<span class="keyword">var</span> sum = <span class="number">0</span></span><br><span class="line">		<span class="keyword">for</span>(a &lt;- arr) &#123;</span><br><span class="line">			sum += a</span><br><span class="line">		&#125;</span><br><span class="line">		sum</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>说明：</p>
<ol>
<li><p>scala中的可变参数和java有一点不同，上例中第三个函数和第四个函数，在java中实际上是同一个函数，而在scala中是两个不同的函数。</p>
</li>
<li><p>在对函数add(arr:Int*)就不能向java一样，直接传递一个数组，否则报错，类型不匹配。要想给一个可变参数传递数组，就需要将数组中的元素提取出来，再传递，操作方式如下：</p>
<blockquote>
<p>val arr = Array(3, 4, 5)<br>ret = add(arr: _*)</p>
</blockquote>
</li>
</ol>
<h1 id="7-scala数组和集合"><a href="#7-scala数组和集合" class="headerlink" title="7. scala数组和集合"></a>7. scala数组和集合</h1><p>​    scala的集合分为了两类，一类是可变的集合（集合可以执行增删改查操作），另一类是不可变集合（集合元素在初始化的时候确定，后续只能进行查，有的可以进行修改，有的不可以）。二者可能名称一样，但是在不同的包下面，对应的包为：scala.collection.mutable和scala.collection.immutable。</p>
<p>​    scala默认使用的集合，或者默认导入的包是immutable。</p>
<p>​    说明：这里提到的可变或者不可变，指的是容器内部的内容，以及容器的长度可变或者不可变。</p>
<h2 id="7-1-Scala数组"><a href="#7-1-Scala数组" class="headerlink" title="7.1. Scala数组"></a>7.1. Scala数组</h2><h3 id="7-1-1-不可变数组Array"><a href="#7-1-1-不可变数组Array" class="headerlink" title="7.1.1. 不可变数组Array"></a>7.1.1. 不可变数组Array</h3><p>​    Array可以理解为java中的数组。</p>
<ol>
<li><p>数组的定义</p>
 <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">java中数组的定义：</span><br><span class="line">	<span class="keyword">new</span> int[<span class="number">5</span>]; </span><br><span class="line">    int[] aa = &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>&#125;; </span><br><span class="line">    int[] bb = <span class="keyword">new</span> int[]&#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>&#125;</span><br><span class="line">scala中数组的定义：</span><br><span class="line">    <span class="keyword">val</span> array = <span class="keyword">new</span> <span class="type">Array</span>[类型（比如<span class="type">Int</span>/<span class="type">Long</span>）](<span class="number">5</span>) ---&gt;定义了一个长度为<span class="number">5</span>的<span class="type">Int</span>/<span class="type">Long</span>类型的数组，每一个元素都有默认值：<span class="number">0</span>。</span><br><span class="line">    <span class="keyword">val</span> array = <span class="type">Array</span>(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>) --&gt;定义类一个初始化内容为<span class="number">1</span>， <span class="number">2</span>， <span class="number">3</span>， <span class="number">4</span>， <span class="number">5</span>的<span class="type">Int</span>类型的数组。</span><br><span class="line">	其中第二种的定义方式，没有<span class="keyword">new</span>关键，其实是<span class="class"><span class="keyword">class</span> <span class="title">Array的伴生对象的构建方式。</span></span></span><br></pre></td></tr></table></figure>
</li>
<li><p>获取数组中的元素</p>
 <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">数组名(index)</span><br><span class="line">比如：</span><br><span class="line"><span class="keyword">val</span> ele = array(<span class="number">3</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>元素的遍历</p>
 <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(ele &lt;- 数组) &#123;</span><br><span class="line">    。。。    </span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">for</span>(i &lt;- array) &#123;</span><br><span class="line">    println(i)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>数组的长度</p>
 <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">array.length</span><br><span class="line">array.size</span><br></pre></td></tr></table></figure>
</li>
<li><p>数组判断</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">判断元素是否包含</span><br><span class="line">array.contains(ele)</span><br><span class="line">eg:</span><br><span class="line">println(<span class="string">&quot;判断元素-3时候在数组中存在：&quot;</span> + array.contains(<span class="number">-2</span>))</span><br></pre></td></tr></table></figure>
</li>
<li><p>数组元素的拼接输出</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">使用数组的方法：mkString</span><br><span class="line"><span class="comment">//拼接数组元素，没有分隔符</span></span><br><span class="line">println(<span class="string">&quot;数组元素：&quot;</span> + array.mkString)</span><br><span class="line"><span class="comment">//拼接数组元素，使用分隔符&quot;, &quot;</span></span><br><span class="line">println(<span class="string">&quot;数组元素：&quot;</span> + array.mkString(<span class="string">&quot;, &quot;</span>))</span><br><span class="line"><span class="comment">//拼接数组元素，使用分隔符&quot;, &quot;,起始字符为[,终止字符为]</span></span><br><span class="line">println(<span class="string">&quot;数组元素：&quot;</span> + array.mkString(<span class="string">&quot;[&quot;</span>, <span class="string">&quot;, &quot;</span>, <span class="string">&quot;]&quot;</span>))</span><br></pre></td></tr></table></figure>

<blockquote>
<p>  数组元素：123-35<br>  数组元素：1, 2, 3, -3, 5<br>  数组元素：[1, 2, 3, -3, 5]</p>
</blockquote>
</li>
</ol>
<h3 id="7-1-2-可变数组ArrayBuffer"><a href="#7-1-2-可变数组ArrayBuffer" class="headerlink" title="7.1.2. 可变数组ArrayBuffer"></a>7.1.2. 可变数组ArrayBuffer</h3><p>​    ArrayBuffer就可以理解为java中的ArrayList。</p>
<ol>
<li><p>定义</p>
 <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//定义一个Int类型的可变数组</span></span><br><span class="line"><span class="keyword">val</span> arrayBuffer = <span class="keyword">new</span> <span class="type">ArrayBuffer</span>[<span class="type">Int</span>]()</span><br><span class="line"><span class="comment">//定义一个String类型的可变数组</span></span><br><span class="line"><span class="keyword">val</span> arrayBuffer = <span class="type">ArrayBuffer</span>[<span class="type">String</span>]()</span><br><span class="line"><span class="comment">//定义一个String类型的初始长度为16的可变数组</span></span><br><span class="line"><span class="keyword">val</span> arrayBuffer = <span class="type">ArrayBuffer</span>[<span class="type">String</span>](<span class="number">16</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>crud</p>
 <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//crud</span></span><br><span class="line"><span class="comment">//增</span></span><br><span class="line">println(<span class="string">&quot;----------arraybuffer的增的操作--------------&quot;</span>)</span><br><span class="line">ab.append(<span class="number">1</span>)</span><br><span class="line">println(<span class="string">&quot;ab.append(1): &quot;</span> + ab)</span><br><span class="line">ab.append(<span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>)</span><br><span class="line">println(<span class="string">&quot;ab.append(2, 3, 4): &quot;</span> + ab)</span><br><span class="line"><span class="comment">//insert(index, ele*)在指定的索引位置上插入一个或多个元素</span></span><br><span class="line">ab.insert(<span class="number">2</span>, <span class="number">-3</span>, <span class="number">-2</span>)</span><br><span class="line">println(<span class="string">&quot;ab.insert(2, -3, -2): &quot;</span> + ab)</span><br><span class="line"><span class="comment">//查</span></span><br><span class="line"><span class="comment">//获取指定索引位置的元素</span></span><br><span class="line"><span class="keyword">val</span> ele = ab(<span class="number">5</span>)</span><br><span class="line">println(<span class="string">&quot;ab(5): &quot;</span> + ele)</span><br><span class="line"><span class="comment">//数组长度</span></span><br><span class="line">println(<span class="string">&quot;可变数组ab的长度：&quot;</span> + ab.size)</span><br><span class="line"><span class="comment">//改</span></span><br><span class="line">ab(<span class="number">5</span>) = <span class="number">-5</span></span><br><span class="line">println(<span class="string">&quot;修改之后的数组为：&quot;</span> + ab)</span><br><span class="line"><span class="comment">//删</span></span><br><span class="line">ab.remove(<span class="number">3</span>)<span class="comment">//删除指定索引位置上的元素</span></span><br><span class="line">println(<span class="string">&quot;ab.remove(3): &quot;</span> + ab)</span><br><span class="line">ab.remove(<span class="number">2</span>, <span class="number">2</span>)<span class="comment">//remove(index, count)从指定索引index位置开始删除，删除count个元素</span></span><br><span class="line">println(<span class="string">&quot;ab.remove(2, 2): &quot;</span> + ab)</span><br><span class="line"><span class="comment">//drop</span></span><br><span class="line"><span class="keyword">var</span> newAb = ab.drop(<span class="number">2</span>)</span><br><span class="line">println(<span class="string">&quot;ab.drop(2): &quot;</span> + ab)</span><br><span class="line">println(<span class="string">&quot;ab.drop(2): &quot;</span> + newAb)</span><br><span class="line">newAb = ab.dropRight(<span class="number">2</span>)</span><br><span class="line">println(<span class="string">&quot;ab.dropRight(2): &quot;</span> + ab)</span><br><span class="line">println(<span class="string">&quot;ab.dropRight(2): &quot;</span> + newAb)</span><br></pre></td></tr></table></figure>
</li>
<li><p>遍历和长度</p>
<p> 遍历和Array方式一样。</p>
<p> 长度可以使用length，也可以使用size。</p>
 <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (i &lt;- ab) &#123;</span><br><span class="line">    print(i + <span class="string">&quot;\t&quot;</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>拼接数组字符串</p>
 <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ab.mkString(<span class="string">&quot;[&quot;</span>, <span class="string">&quot;, &quot;</span>, <span class="string">&quot;]&quot;</span>)</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h3 id="7-1-3-Array和ArrayBuffer的一些基本通用操作"><a href="#7-1-3-Array和ArrayBuffer的一些基本通用操作" class="headerlink" title="7.1.3. Array和ArrayBuffer的一些基本通用操作"></a>7.1.3. Array和ArrayBuffer的一些基本通用操作</h3><ol>
<li><p>包含</p>
 <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ab.contains(ele) 判断元素是否包含</span><br></pre></td></tr></table></figure>
</li>
<li><p>数组求和</p>
 <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">调用数组的函数sum</span><br><span class="line">println(<span class="string">&quot;数组求和&quot;</span> + ab.sum)</span><br></pre></td></tr></table></figure>
</li>
<li><p>数组的最大值最小值</p>
 <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">调用数组的函数max和min</span><br><span class="line">println(<span class="string">&quot;最大值：&quot;</span> + ab.max)</span><br><span class="line">println(<span class="string">&quot;最小值：&quot;</span> + ab.min)</span><br></pre></td></tr></table></figure>
</li>
<li><p>Array和ArrayBuffer之间的互相转换</p>
<p> 类似java中数组和ArrayList之间的转换</p>
 <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">java版本</span><br><span class="line">	数组---&gt;<span class="type">List</span>：<span class="type">Arrays</span>.asList(array)</span><br><span class="line">	<span class="type">List</span>---&gt;数组：list.toArray(<span class="keyword">new</span> <span class="type">Xxx</span>[list.size()])</span><br><span class="line">scala版本</span><br><span class="line">	<span class="type">Array</span>---&gt;<span class="type">ArrayBuffer</span>：array.toBuffer</span><br><span class="line">	<span class="type">ArrayBuffer</span>---&gt;<span class="type">Array</span>：ab.toArray</span><br></pre></td></tr></table></figure>
</li>
<li><p>数组内容的显示</p>
 <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mkString(start, sep, end)</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h2 id="7-2-Scala集合"><a href="#7-2-Scala集合" class="headerlink" title="7.2. Scala集合"></a>7.2. Scala集合</h2><h3 id="7-2-1-Map映射"><a href="#7-2-1-Map映射" class="headerlink" title="7.2.1 Map映射"></a>7.2.1 Map映射</h3><p>​    Map是一个对偶，映射的k-v键值对的集合，在一个map中可以包含若干组k-v映射关系，前提条件是k不能重复。同样map也有可变和不可变之分。</p>
<h4 id="7-2-1-1-不可变Map"><a href="#7-2-1-1-不可变Map" class="headerlink" title="7.2.1.1 不可变Map"></a>7.2.1.1 不可变Map</h4><p>​    import scala.collection.immutable.Map</p>
<ol>
<li><p>定义</p>
<p> 因为Map是一个类似java中的接口，无法直接创建对象，所以需要使用它的伴生对象创建。</p>
 <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">val</span> map = <span class="type">Map</span>[<span class="type">Type1</span>, <span class="type">Type2</span>]()</span><br><span class="line">创建了一个key的类型为<span class="type">Type1</span>，value的类型为<span class="type">Type2</span>的map映射</span><br></pre></td></tr></table></figure>
</li>
<li><p>初始化</p>
 <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">不可变的map的数组，只能在初始化的时候指定</span><br><span class="line">val map &#x3D; Map[Type1, Type2](</span><br><span class="line">	(k1 -&gt; v1),</span><br><span class="line">	(k2 -&gt; v2),</span><br><span class="line">    。。。</span><br><span class="line">)</span><br><span class="line">或者</span><br><span class="line">val map &#x3D; Map[Type1, Type2](</span><br><span class="line">	k1 -&gt; v1,</span><br><span class="line">	k2 -&gt; v2,</span><br><span class="line">    。。。</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
</li>
<li><p>crud</p>
 <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//国家---&gt;首都</span></span><br><span class="line"><span class="keyword">val</span> capital = <span class="type">Map</span>[<span class="type">String</span>, <span class="type">String</span>](</span><br><span class="line">    (<span class="string">&quot;china&quot;</span> -&gt; <span class="string">&quot;BJ&quot;</span>),</span><br><span class="line">    <span class="string">&quot;japan&quot;</span> -&gt; <span class="string">&quot;tokyo&quot;</span>,</span><br><span class="line">    <span class="string">&quot;south korea&quot;</span> -&gt; <span class="string">&quot;汉城&quot;</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="comment">//crud</span></span><br><span class="line"><span class="comment">//增 不可变的map不能追加</span></span><br><span class="line"><span class="comment">//		capital += (&quot;usa&quot; -&gt; &quot;wc&quot;)</span></span><br><span class="line"><span class="comment">//		capital(&quot;usa&quot;) = &quot;wc&quot;</span></span><br><span class="line"><span class="comment">//删除</span></span><br><span class="line"><span class="keyword">val</span> ret = capital.drop(<span class="number">1</span>)<span class="comment">//原来的集合不会发生变化</span></span><br><span class="line">println(<span class="string">&quot;capital.drop(1)返回值：&quot;</span> + ret)</span><br><span class="line">println(<span class="string">&quot;capital.drop(1)之后的map：&quot;</span> + capital)</span><br><span class="line"><span class="comment">//该</span></span><br><span class="line"><span class="comment">//		capital(&quot;china&quot;) = &quot;wc&quot;</span></span><br><span class="line"><span class="comment">//查</span></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">	map.get(key)</span></span><br><span class="line"><span class="comment">		返回值类Some或者None</span></span><br><span class="line"><span class="comment">		也就是如果key在map中存在返回Some，意思就是存在</span></span><br><span class="line"><span class="comment">		反之返回None</span></span><br><span class="line"><span class="comment">	总结：value也就是可能有值，也可能没有值</span></span><br><span class="line"><span class="comment">	scala中把这种可能有之，也可能没有值通过一个类Option[T]来表示</span></span><br><span class="line"><span class="comment">	Option有两个子类：Some(T)和None</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line">println(<span class="string">&quot;capital.get(\&quot;japan\&quot;): &quot;</span> + capital.get(<span class="string">&quot;japan&quot;</span>))</span><br><span class="line">println(<span class="string">&quot;capital.get(\&quot;uk\&quot;): &quot;</span> + capital.get(<span class="string">&quot;uk&quot;</span>))</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">	既然get的返回值是Option，也就是无法直接过去value，要想获取value，就需要调用option.get()</span></span><br><span class="line"><span class="comment">	java.util.NoSuchElementException: None.get</span></span><br><span class="line"><span class="comment">	同时需要注意的是，get只能对some操作，对None操作会抛异常：NoSuchElementException</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line">println(<span class="string">&quot;capital.get(\&quot;japan\&quot;): &quot;</span> + capital.get(<span class="string">&quot;japan&quot;</span>).get)</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">	获取元素的方式二</span></span><br><span class="line"><span class="comment">	java.util.NoSuchElementException: key not found: uk</span></span><br><span class="line"><span class="comment">	key不存在会报错</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line">println(<span class="string">&quot;capital(\&quot;japan\&quot;): &quot;</span> + capital(<span class="string">&quot;japan&quot;</span>))</span><br><span class="line"><span class="comment">//println(&quot;capital(\&quot;uk\&quot;): &quot; + capital(&quot;uk&quot;))</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//推荐使用，</span></span><br><span class="line"><span class="keyword">val</span> countryC = capital.getOrElse(<span class="string">&quot;china&quot;</span>, <span class="string">&quot;DBJ&quot;</span>)</span><br><span class="line">println(countryC)</span><br><span class="line"><span class="comment">//判断</span></span><br><span class="line"><span class="keyword">if</span>(capital.contains(<span class="string">&quot;uk&quot;</span>)) &#123;</span><br><span class="line">    println(<span class="string">&quot;capital(\&quot;uk\&quot;): &quot;</span> + capital(<span class="string">&quot;uk&quot;</span>))</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//长度</span></span><br><span class="line">capital.size</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h4 id="7-2-1-2-可变Map"><a href="#7-2-1-2-可变Map" class="headerlink" title="7.2.1.2. 可变Map"></a>7.2.1.2. 可变Map</h4><p>import scala.collection.mutable.Map</p>
<ol>
<li><p>定义并初始化</p>
 <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">val</span> map = mutable.<span class="type">Map</span>[<span class="type">Type1</span>, <span class="type">Type2</span>](</span><br><span class="line">	(k1 -&gt; v1),</span><br><span class="line">	(k2 -&gt; v2),</span><br><span class="line">    。。。</span><br><span class="line">)</span><br><span class="line">创建了一个map，key的类型<span class="type">Type1</span>，value的类型<span class="type">Type2</span>，并且提供了初始化k-v键值对，当然可可以去掉其中的k-v，因为是可变的，那么便可以进行后续的元素追加。</span><br></pre></td></tr></table></figure>
</li>
<li><p>crud</p>
 <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">pc += (<span class="string">&quot;广东&quot;</span> -&gt; <span class="string">&quot;粤&quot;</span>)</span><br><span class="line">pc += (<span class="string">&quot;湖南&quot;</span> -&gt; <span class="string">&quot;湘&quot;</span>)</span><br><span class="line">pc += (<span class="string">&quot;湖北&quot;</span> -&gt; <span class="string">&quot;鄂&quot;</span>)</span><br><span class="line">pc += (<span class="string">&quot;广东&quot;</span> -&gt; <span class="string">&quot;粤&quot;</span>)</span><br><span class="line">pc(<span class="string">&quot;广西&quot;</span>) = <span class="string">&quot;桂&quot;</span></span><br><span class="line">println(pc)</span><br><span class="line"><span class="comment">//修改</span></span><br><span class="line">pc(<span class="string">&quot;广西&quot;</span>) = <span class="string">&quot;桂桂&quot;</span></span><br><span class="line"><span class="comment">//获取</span></span><br><span class="line">println(pc.getOrElse(<span class="string">&quot;江西&quot;</span>, <span class="string">&quot;兰州&quot;</span>))</span><br><span class="line"><span class="comment">//删除</span></span><br><span class="line">println(pc.remove(<span class="string">&quot;广东&quot;</span>))</span><br><span class="line">println(pc)</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h4 id="7-2-1-3-map的通用操作"><a href="#7-2-1-3-map的通用操作" class="headerlink" title="7.2.1.3. map的通用操作"></a>7.2.1.3. map的通用操作</h4><ol>
<li><p>集合大小</p>
 <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">map.size</span><br></pre></td></tr></table></figure>
</li>
<li><p>map的遍历</p>
 <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">* java版本</span></span><br><span class="line"><span class="comment">* for(Map.Entry&lt;K, V&gt; me : map.entrySet) &#123;</span></span><br><span class="line"><span class="comment">*     me.getKey</span></span><br><span class="line"><span class="comment">*     me.getValue</span></span><br><span class="line"><span class="comment">* &#125;</span></span><br><span class="line"><span class="comment">* for(K key : map.keySet()) &#123;</span></span><br><span class="line"><span class="comment">*     V v = map.get(key);</span></span><br><span class="line"><span class="comment">* &#125;</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">for</span>((k, v) &lt;- pc) &#123;</span><br><span class="line">    println(<span class="string">&quot;key: &quot;</span> + k + <span class="string">&quot;,value: &quot;</span> + v)</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">for</span>(kv &lt;- pc) &#123;</span><br><span class="line">    println(kv)</span><br><span class="line">&#125;</span><br><span class="line">println(<span class="string">&quot;------foreach遍历---------&quot;</span>)</span><br><span class="line"><span class="comment">//函数式编程的foreach遍历</span></span><br><span class="line">pc.foreach(kv =&gt; &#123;</span><br><span class="line">    println(kv)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h3 id="7-2-2-Tuple元组"><a href="#7-2-2-Tuple元组" class="headerlink" title="7.2.2 Tuple元组"></a>7.2.2 Tuple元组</h3><ol>
<li>定义</li>
</ol>
<p>​    元组，其实就是一组对偶，也可以理解为是java中List<Object>。映射是键／值对偶的集合。对偶足元组( tuple)的最简单形态，元组是不同类型的值的聚集。<strong>元组的值是通过将单个的值包含在圆括号中构成的</strong>。例如：(1, 3.14, “Fred”)是一个元组，类型为：Tuple3 [Int, Double, java.lang.String]</Object></p>
<ol start="2">
<li><p>创建并初始化</p>
<p> 说明：元组Tuple是List<Object>，但是其长度是有范围的，最长可以容纳22个元素，也即Tuple22,其中Tuple1可以简写为Tuple。</Object></p>
 <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//元组只能在创建的时候进行初始化</span></span><br><span class="line"><span class="keyword">val</span> tuple1 = <span class="keyword">new</span> <span class="type">Tuple1</span>[<span class="type">Int</span>](<span class="number">1</span>)</span><br><span class="line"><span class="keyword">val</span> tuple2 = <span class="keyword">new</span> <span class="type">Tuple2</span>[<span class="type">Int</span>, <span class="type">Double</span>](<span class="number">1</span>, <span class="number">3.14</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>操作</p>
 <figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//获取元组的值</span></span><br><span class="line"><span class="comment">//获取第一个</span></span><br><span class="line">println(<span class="string">&quot;tuple2._1: &quot;</span> + tuple2._1)</span><br><span class="line"><span class="comment">//获取第二个</span></span><br><span class="line">println(<span class="string">&quot;tuple2._2: &quot;</span> + tuple2._2)</span><br><span class="line"><span class="comment">//获取第N(1 &lt;= N &lt;= 22)个</span></span><br><span class="line"><span class="comment">//		tuple2._N</span></span><br><span class="line"><span class="comment">//		tuple2._2 = 4.35 //不可以修改</span></span><br><span class="line"><span class="comment">//遍历 元组不可以直接进行遍历</span></span><br><span class="line"><span class="keyword">for</span>(t &lt;- tuple2.productIterator) &#123;</span><br><span class="line">    println(t)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>比较常见的定义元组的方式</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//更常见的元组的定义</span></span><br><span class="line"><span class="keyword">val</span> season = <span class="comment">/*new Tuple4[String, String, String, String]*/</span>(<span class="string">&quot;spring&quot;</span>, <span class="string">&quot;summer&quot;</span>, <span class="string">&quot;autumn&quot;</span>, <span class="string">&quot;winter&quot;</span>)</span><br><span class="line">season._2</span><br><span class="line"><span class="comment">//最常见的定义方式</span></span><br><span class="line"><span class="keyword">val</span> (spring, summer, autumn, winter) = (<span class="string">&quot;spring&quot;</span>, <span class="string">&quot;summer&quot;</span>, <span class="string">&quot;autumn&quot;</span>, <span class="string">&quot;winter&quot;</span>)</span><br><span class="line">println(spring)</span><br><span class="line">println(summer)</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h3 id="7-2-3-Zip拉链操作"><a href="#7-2-3-Zip拉链操作" class="headerlink" title="7.2.3. Zip拉链操作"></a>7.2.3. Zip拉链操作</h3><p>​    zip操作，就是将两个单列的集合，组合成双列的集合，集合中的每一组元素就是上述学习过的tuple。</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">val</span> province = <span class="type">Array</span>(<span class="string">&quot;山东&quot;</span>, <span class="string">&quot;河南&quot;</span>, <span class="string">&quot;陕西&quot;</span>, <span class="string">&quot;福建&quot;</span>)</span><br><span class="line"><span class="keyword">val</span> capital = <span class="type">Array</span>(<span class="string">&quot;济南&quot;</span>, <span class="string">&quot;郑州&quot;</span>, <span class="string">&quot;西安&quot;</span>, <span class="string">&quot;福州&quot;</span>, <span class="string">&quot;桂林&quot;</span>)</span><br><span class="line"><span class="comment">//zip 拉链操作</span></span><br><span class="line"><span class="keyword">val</span> pcs = province.zip(capital)</span><br><span class="line"><span class="keyword">for</span>((p, c) &lt;- pcs) &#123;</span><br><span class="line">    println(p + <span class="string">&quot;---&gt;&quot;</span> + c)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>特点：</p>
<p>​    在组合两个集合的时候，集合元素两两一一对应，如果两个集合的长度不一致，将超过的部分,或者没有匹配上的部分进行裁剪，丢弃。</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/yuanyongjie/blog.git/2020/08/31/day01/" data-id="ckeia6jz50003usuwe7716ye7" class="article-share-link">Share</a>
      
      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
  
    <a href="/blog/2020/08/31/test-1/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">test</div>
    </a>
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    

  
    

  
    
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2020/08/">August 2020</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/blog/2020/08/31/day01/">(no title)</a>
          </li>
        
          <li>
            <a href="/blog/2020/08/31/test-1/">test</a>
          </li>
        
          <li>
            <a href="/blog/2020/08/31/test/">test</a>
          </li>
        
          <li>
            <a href="/blog/2020/08/31/hello-world/">Hello World</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2020 John Doe<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/blog/" class="mobile-nav-link">Home</a>
  
    <a href="/blog/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>


  
<link rel="stylesheet" href="/blog/fancybox/jquery.fancybox.css">

  
<script src="/blog/fancybox/jquery.fancybox.pack.js"></script>




<script src="/blog/js/script.js"></script>




  </div>
</body>
</html>